from django.shortcuts import render
from django.views import View
from authentication.libls.captcha.captcha import captcha
from django_redis import get_redis_connection
from django import http
from ershou_shop.utils.response_code import RETCODE
from celery_tasks.sms.tasks import sent_sms_code
from authentication.libls.yuntongxun.ccp_sms import CCP
import random
# Create your views here.


class ImageAuth(View):
    '''图片验证码识别系统'''
    def get (self,request,uuid):
        # 1.接收参数

        # 2.校验参数

        #3.实现主体业务逻辑，生成，相应，保存
        text,image = captcha.generate_captcha()
        redies_con=get_redis_connection('image_code')
        redies_con.setex('img_%s' %uuid,'300',text)
        #4.返回响应
        print(text)
        return http.HttpResponse(image,content_type='image/jpg')

class MobleAuth(View):
    def get(self,request,moble):
    #1.接受参数
        code = request.GET.get('image_code')
        uuid = request.GET.get('uuid')
    #2.校验参数
        if not all([code,uuid]):
            return http.HttpResponseForbidden('缺少必传参数')
        #3.主题逻辑
        #3.1校验正确性
        redies_con1=get_redis_connection('image_code')
        pl = redies_con1.pipeline()
        image_code = redies_con1.get('img_%s' % uuid)
        if image_code is None:
            return  http.JsonResponse({'code':RETCODE.IMAGECODEERR,'errmsg':'图形验证码已经失效'})
        pl.delete('img_%s' % uuid) #删除图形验证码
        #将bytes转为字符串
        image_code =image_code.decode()
        #判断输如验证码是否正确
        if image_code.lower()!= code.lower():
            return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '图形验证码输如错误'})
        #生成验证码
        sms_code='%06d' %random.randint(0,999999)
        pl.setex('sms_%s'%moble,300,sms_code)
        #避免用户提前发送验证码

        aa=redies_con1.get('sms_aa_%s' % moble)
        print(type(aa))
        print(aa)
        if aa==b'1':
           return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '请不要频繁发送'})
        else:
            pl.setex('sms_aa_%s'%moble,20,1)
            # 发送图形验证码
            sent_sms_code.delay(moble,sms_code)

        pl.execute()
        #4.返回相应
        return http.JsonResponse({'code':RETCODE.OK,'errmsg':'发送短信成功'})



